package com.vx.cloud.dataCloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 消费者服务service,
 * Created by aofavx on 2017-8-9.
 */
@Service
public class ConsumerService {

    @GetMapping("/consumer")
    @HystrixCommand(fallbackMethod = "errFun", commandProperties = {
            //设置熔断器等待的链接时长100毫秒，超过这个时长没有得到数据，就执行错误处理
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "100"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "50")

    })
    public String consumer() throws Exception {
        int l = new Random().nextInt(200);
        System.out.println(String.format("l=%s", l));
        TimeUnit.MILLISECONDS.sleep(l);
        return "ok";
    }

    @GetMapping("/consumer2")
    @HystrixCommand(fallbackMethod = "errFun", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "100"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "50")

    })
    public String consumer2() throws Exception {
        int l = new Random().nextInt(200);
        System.out.println(String.format("l=%s", l));
        TimeUnit.MILLISECONDS.sleep(l);
        return "ok";
    }


    public String errFun(Throwable e) {
        System.out.println("execute okFallback!" + e.getMessage());
        System.out.println("error");
        return "fallback";
    }
    /**
     * 如果接口调用失败，则执行此方法
     */
    public String errFun() {
        return "errFun获取接口数据错误";
    }
}
